package com.example.richobject;

import java.nio.charset.Charset;

/**
 * Created by zlq on 2018-05-17.
 */

public class ByteUtil {

    public static byte[] shortToByteArray(short s) {
        byte[] targets = new byte[2];
        for (int i = 0; i < 2; i++) {
            int offset = (targets.length - 1 - i) * 8;
            targets[i] = (byte) ((s >> offset) & 0xff);
        }
        return targets;
    }

    /**
     * int转换成byte数组
     * @param number int型数据
     * @return byte数组
     */
    public static byte[] intToByte(int number) {
        int temp = number;
        byte[] b = new byte[4];
        for (int i = 0; i < b.length; i++) {
            b[i] = new Integer(temp & 0xff).byteValue();
            // 将最低位保存在最低位
            temp = temp >> 8; // 向右移8位
        }
        return b;
    }

    /**
     * byte数组转换成int
     * @param b byte数组
     * @return int型数据
     */
    public static int byteToInt(byte[] b) {
        int s = 0;
        int s0 = b.length > 0 ? b[0] & 0xff : 0;// 最低位
        int s1 = b.length > 1 ? b[1] & 0xff : 0;
        int s2 = b.length > 2 ? b[2] & 0xff : 0;
        int s3 = b.length > 3 ? b[3] & 0xff : 0;
        s3 <<= 24;
        s2 <<= 16;
        s1 <<= 8;
        s = s0 | s1 | s2 | s3;
        return s;
    }

    public static String dumpByte(byte[] data, int length) {
        if (null == data) {
            return null;
        }
        String print = "";
        for (int i = 0; i < data.length && i < length; i++) {
            byte temp = data[i];
            String hex = Integer.toHexString(temp & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            print = print + "0x" + hex.toUpperCase() + ", ";
        }
        return print;
    }

    /**
     * byte转bit数组
     * @param b
     * @return
     */
    public static byte[] byteToBitArray(byte b) {
        byte[] bitArray = new byte[8];

        bitArray[0] = (byte) ((b >> 7) & 0x1);
        bitArray[1] = (byte) ((b >> 6) & 0x1);
        bitArray[2] = (byte) ((b >> 5) & 0x1);
        bitArray[3] = (byte) ((b >> 4) & 0x1);
        bitArray[4] = (byte) ((b >> 3) & 0x1);
        bitArray[5] = (byte) ((b >> 2) & 0x1);
        bitArray[6] = (byte) ((b >> 1) & 0x1);
        bitArray[7] = (byte) (b & 0x1);

        return bitArray;
    }

    public static byte bitArrayToByte(byte[] bit) {
        if (bit == null || bit.length != 8) {
            return 0xffffffff;
        }
        return (byte) ((((bit[0] & 0x1) << 7) | ((bit[1] & 0x1) << 6) | ((bit[2] & 0x1) << 5) | ((bit[3] & 0x1) << 4) |
                ((bit[4] & 0x1) << 3) | ((bit[5] & 0x1) << 2) | ((bit[6] & 0x1) << 1) | ((bit[7] & 0x1))) & 0xff);
    }

    public static String getString(byte[] bytes, String charsetName) {
        return new String(bytes, Charset.forName(charsetName));
    }

    public static String getString(byte[] bytes) {
        return getString(bytes, "GBK");
    }
}